package com.css.fxfzcpxx.modules.categoryView.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.css.fxfzcpxx.base.attachment.service.AttachmentInfoService;
import com.css.fxfzcpxx.modules.categoryView.param.QueParam;
import com.css.fxfzcpxx.modules.categoryView.service.CategoryViewService;
import com.css.fxfzcpxx.modules.categoryView.vo.CategoryViewVo;
import com.css.fxfzcpxx.modules.courseManage.repository.CourseManageRepository;
import com.css.fxfzcpxx.modules.earthquakeDisaster.repository.EarthquakeDisasterRepository;
import com.css.fxfzcpxx.modules.informationAchievement.repository.InfAchievementRepository;
import com.css.fxfzcpxx.modules.informationDelivery.repository.InfDeliveryRepository;
import com.css.fxfzcpxx.modules.serviceCase.repository.ServiceCaseRepository;
import com.css.fxfzcpxx.modules.thematicMap.entity.AchManageEntity;
import com.css.fxfzcpxx.modules.thematicMap.repository.TheMapRepository;
import com.css.fxfzcpxx.util.PlatformObjectUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author:
 * @CreateTime: 2023/9/12 15:16
 * @Description:
 */
@Service
public class CategoryViewServiceImpl implements CategoryViewService {

    @Resource
    private TheMapRepository theMapRepository;

    @Resource
    InfAchievementRepository infAchievementRepository;

    @Resource
    InfDeliveryRepository infDeliveryRepository;

    @Resource
    AttachmentInfoService attachmentInfoService;

    @Resource
    ServiceCaseRepository serviceCaseRepository;

    @Resource
    private EarthquakeDisasterRepository earthquakeDisasterRepository;

    @Resource
    RestTemplate restTemplate;


    @Override
    public Map<String,Object> getPage(QueParam queParam, int curPage, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        String module1 = queParam.getModule1();
        List<CategoryViewVo> list=new ArrayList<>();
        if("全部分类".equals(module1)){

            List<CategoryViewVo> theMapList=theMapRepository.getData(queParam);
            for(CategoryViewVo item:theMapList){
                item.setModule2(item.getModule2().substring(item.getModule2().indexOf("-")+1));
                item.setModule1("专题图");
            }
            List<CategoryViewVo> infAchievementList=infAchievementRepository.getData(queParam);
            for(CategoryViewVo item:infAchievementList){
                item.setModule2(item.getModule2().substring(item.getModule2().indexOf("-")+1));
                item.setModule1("信息成果");
            }
            List<CategoryViewVo> infDeliveryList = infDeliveryRepository.getData(queParam);
            for(CategoryViewVo item:infDeliveryList){
                item.setModule1("知识学习");
            }
            List<CategoryViewVo> hisEarthquakeList = getBasicData(queParam);
            for(CategoryViewVo item:hisEarthquakeList){
                item.setModule1("历史地震");
                item.setModule2("历史地震事件");
            }

            List<CategoryViewVo> earthquakeList=earthquakeDisasterRepository.getData(queParam);
            //List<CategoryViewVo> earthquakeList = getBasicData(queParam, "地震灾害信息");
            for(CategoryViewVo item:earthquakeList){
                item.setModule1("历史地震");
                item.setModule2("地震灾害信息");
            }
            /*List<CategoryViewVo> couManageList = courseManageRepository.getData(queParam);
            for(CategoryViewVo item:couManageList){
                item.setModule1("知识学习");
            }*/
            List<CategoryViewVo> serviceCaseList = serviceCaseRepository.getData(queParam);
            for(CategoryViewVo item:serviceCaseList){
                item.setModule1("服务案例");
            }


            list.addAll(theMapList);
            list.addAll(infAchievementList);
            //list.addAll(couManageList);
            list.addAll(infDeliveryList);
            list.addAll(hisEarthquakeList);
            list.addAll(earthquakeList);
            list.addAll(serviceCaseList);
            List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
            for (CategoryViewVo item:pageList) {
                if (PlatformObjectUtils.isNotEmpty(item.getAttachId())){
                    item.setAttachmentInfo(attachmentInfoService.queryFile(item.getAttachId()));
                }
            }
            // 使用Comparator比较器来排序
            Comparator<CategoryViewVo> comparator = Comparator.comparing(CategoryViewVo::getCreateTime);
            // 调用sort方法对列表进行排序
            Collections.sort(pageList, comparator);


            map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
            map.put("rows", pageList);
        }else{
            if("专题图".equals(module1)){
                list=theMapRepository.getData(queParam);
                List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                for(CategoryViewVo item:pageList){
                    item.setModule2(item.getModule2().substring(item.getModule2().indexOf("-")+1));
                    item.setModule1(module1);
                }
                map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                map.put("rows", pageList);

            }else if("信息成果".equals(module1)){
                list=infAchievementRepository.getData(queParam);
                List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                for(CategoryViewVo item:pageList){
                    item.setModule2(item.getModule2().substring(item.getModule2().indexOf("-")+1));
                    item.setModule1(module1);
                    if (PlatformObjectUtils.isNotEmpty(item.getAttachId())){
                        item.setAttachmentInfo(attachmentInfoService.queryFile(item.getAttachId()));
                    }
                }
                map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                map.put("rows", pageList);

            }else if("历史地震".equals(module1)){
                // TODO: 2023/9/15 需要基础数据接口
                if(PlatformObjectUtils.isNotEmpty(queParam.getModule2())){
                    if("历史地震事件".equals(queParam.getModule2())){
                        list = getBasicData(queParam);
                        List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                        for(CategoryViewVo item:pageList){
                            item.setModule1(module1);
                            item.setModule2(queParam.getModule2());
                        }
                        map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                        map.put("rows", pageList);

                    }else{
                        list = earthquakeDisasterRepository.getData(queParam);;
                        List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                        for(CategoryViewVo item:pageList){
                            item.setModule1(module1);
                            item.setModule2(queParam.getModule2());
                        }
                        map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                        map.put("rows", pageList);
                    }
                }else{
                    List<CategoryViewVo> hisEarthquakeList = getBasicData(queParam);
                    for(CategoryViewVo item:hisEarthquakeList){
                        item.setModule1("历史地震");
                        item.setModule2("历史地震事件");
                    }
                    List<CategoryViewVo> earthquakeList = earthquakeDisasterRepository.getData(queParam);;
                    for(CategoryViewVo item:earthquakeList){
                        item.setModule1("历史地震");
                        item.setModule2("地震灾害信息");
                    }
                    list.addAll(hisEarthquakeList);
                    list.addAll(earthquakeList);
                    List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                    map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                    map.put("rows", pageList);
                }

            }else if("知识学习".equals(module1)){
                /*if("在线课堂".equals(queParam.getModule2())){
                    //无发布单位,无栏目
                    list=courseManageRepository.getData(queParam);
                    List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                    for(CategoryViewVo item:pageList){
                        item.setModule1(module1);
                        item.setModule2(queParam.getModule2());
                    }
                    map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                    map.put("rows", pageList);

                }else{*/
                    list=infDeliveryRepository.getData(queParam);
                    List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                    for(CategoryViewVo item:pageList){
                        item.setModule1(module1);
                        if (PlatformObjectUtils.isNotEmpty(item.getAttachId())){
                            item.setAttachmentInfo(attachmentInfoService.queryFile(item.getAttachId()));
                        }
                    }
                    map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                    map.put("rows", pageList);
                //}

            } else if ("服务案例".equals(module1)) {
                list = serviceCaseRepository.getData(queParam);
                List<CategoryViewVo> pageList = startPage(list, curPage, pageSize);
                for (CategoryViewVo item : pageList) {
                    item.setModule1(module1);
                    if (PlatformObjectUtils.isNotEmpty(item.getAttachId())){
                        item.setAttachmentInfo(attachmentInfoService.queryFile(item.getAttachId()));
                    }
                }
                map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
                map.put("rows", pageList);
            }
        }




        return map;
    }

    private  List<CategoryViewVo> getBasicData(QueParam param){
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("sjxtRestUrl") + "/cpxx/getStrongCatalog";


        JSONObject valueMap = new JSONObject();
        valueMap.put("startTime", param.getStartTime());
        valueMap.put("endTime", param.getEndTime());
        valueMap.put("keyword", param.getKeyword());


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "fxfzcpxx");
        headers.set("subsystemCode", "dzxczhsspgzxt");
        HttpEntity<JSONObject> r = new HttpEntity<>(valueMap, headers);

        //JSONArray data = restTemplate.exchange(url, HttpMethod.POST, r, JSONArray.class).getBody();

        TypeReference<List<CategoryViewVo>> typeRef = new TypeReference<List<CategoryViewVo>>() {};

        ResponseEntity<JSONArray> responseEntity = restTemplate.exchange(url, HttpMethod.POST, r, JSONArray.class);
        JSONArray jsonArray = responseEntity.getBody();
        List<CategoryViewVo> categoryViewVoList = JSON.parseObject(jsonArray.toJSONString(), typeRef);

        return categoryViewVoList;
    }

    private  List<CategoryViewVo> startPage(List<CategoryViewVo> list, Integer pageNum, Integer pageSize) {
        if (list.isEmpty()) {
            return new ArrayList<>();
        }

        int count = list.size();
        //int pageCount = (int) Math.ceil((double) count / pageSize);  // 使用 Math.ceil 计算 pageCount

        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, count);  // 确保 toIndex 不超过列表范围

        return list.subList(fromIndex, toIndex);
    }
}
